/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/
 
import fever.data.validators.Validator;
import fever.events.ValidationResultEvent;
import fever.utils.ASType;
import fever.utils.StringUtil;

/**
 * Validates Number value.
 * 
 * <p>Differents tests can be done :
 * <ul>
 *   <li>min / max</li>
 *   <li>domain (integer or real)</li>
 *   <li>allow negative value</li>
 * </ul>
 * 
 * @see fever.data.validators.Validator
 * 
 * @author Romain Ecarnot
 */
class fever.data.validators.NumberValidator extends Validator
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------

	private static var PROHIBITED_CHARS : Array = [
			" ", "\n", "\r", "\t", "/", "(", ")", "[", "]", "|", "'", "~",
			"&", "=", "!", ";", "%", "¨", "+", "#", "²", "¤", "£", "§", ">", "<", "\\"
			];
	
	private var _precision : Number;
	
	
	//-------------------------------------------------------------------------
	// Public properties
	//-------------------------------------------------------------------------
	
	/** 
	 * Specifies whether negative numbers are permitted.
	 * Valid values are true or false. The default value is true.
	 */
	public var allowNegative : Boolean;
	
	/** 
	 * The character used to separate the whole from the fractional part of the number. 
	 * Cannot be a digit and must be distinct from the thousandsSeparator. 
	 * The default value is ".".
	 */	public var decimalSeparator : String;
	
	/** 
	 * Type of number to be validated. Permitted values are {@link fever.utils.ASType#REAL} 
	 * and {@link fever.utils.ASType#INT}. Default value is {@link fever.utils.ASType#REAL}.
	 */
	public var domain : String;
	
	/**
	 * Maximum value for a valid number. The default value is {@code 'NaN'}, 
	 * which means it is ignored.
	 */
	public var maxValue : Number;
	
	/**
	 * Minimum value for a valid number. The default value is {@code 'NaN'}, 
	 * which means it is ignored.
	 */	public var minValue : Number;
	
	/**
	 * The maximum number of digits allowed to follow the decimal point.
	 * 
	 * <p> Note: Setting to 0 has the same effect as setting domain to 
	 * {@link fever.utils.ASType#INT}. 
	 * The default value is {@code 'NaN'}, which means it is ignored.
	 */
	public function get precision() : Number { return _precision; }
	public function set precision( value : Number ) : Void
	{ 
		if(value >= 0)
		{
			_precision = value;
			if(_precision == 0) domain = ASType.INT;	
		}
		else _precision = Number.NaN;
		
	}
	
	/**
	 * The character used to separate thousands in the whole part of the number.
	 */	public var thousandsSeparator : String;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	public function NumberValidator()
	{
		allowNegative = true;
		decimalSeparator = ".";
		domain = ASType.REAL;
		maxValue = Number.NaN;
		minValue = Number.NaN;		precision  = Number.NaN;
		thousandsSeparator = ",";
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private function _doValidation(object) : ValidationResultEvent
	{
		var o = _buildValidationTarget(object);
		var toValid : Number;
		var targetType : String = typeof(o);
		
		switch(true)
		{
			case ( targetType == ASType.STRING ) :
				if( !_testFormatString(o) )
				{
					_fireEventType( ValidationResultEvent.INVALID );
					return _event;	
				}
				toValid = _buildTargetByString(o);
				break;
			case ( targetType == ASType.NUMBER) :
				toValid = Number(o);
				break;
			default : 
				toValid =  _buildTargetByString( o.toString() );
		}
		
		if( !_testRequired( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( !_testNegative( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( !_testDomain( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( !_testMaxValue( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( !_testMinValue( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		if( !_testPrecision( toValid ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		_prepareEvent( ValidationResultEvent.VALID, toValid, "");
		_fireEventType( ValidationResultEvent.VALID );
		
		return _event;
	}
	
	private function _buildTargetByString( source : String ) : Number
	{
		var result : Number;
			
		if( source.indexOf( decimalSeparator ) > 0)
		{
			result = parseFloat( source );
		}
		else if( source.indexOf( thousandsSeparator ) > 0 )
		{
			result = parseFloat( StringUtil.replace(source, ",", ".") );	
		}
		
		return result;
	}
	
	private function _testRequired(s) : Boolean
	{
		if(required && ( s == undefined || s == null || isNaN(s)) )
		{
			_prepareEvent( ValidationResultEvent.INVALID, s, _resources.required_field_error );
			return false;
		}
		return true;
	}
	
	private function _testFormatString( source : String) : Boolean
	{
		if( source.split( decimalSeparator ).length > 2 )
		{
			_prepareEvent( ValidationResultEvent.INVALID, source, _resources.number_decimal_counter_error );
			return false;
		}
		if( source.split( thousandsSeparator ).length > 2 )
		{
			_prepareEvent( ValidationResultEvent.INVALID, source, _resources.number_separator_error );
			return false;
		}
		
		var i = 27;
		while(--i > 0)
		{
			if( StringUtil.contains( source, PROHIBITED_CHARS[i] ) )	
			{
				_prepareEvent( ValidationResultEvent.INVALID, source, _resources.number_invalid_char_error );
				return false;
			}
		}
		
		return true;
	}
	
	private function _testNegative(n : Number) : Boolean
	{
		if( !allowNegative && n < 0)
		{
			_prepareEvent( ValidationResultEvent.INVALID, n, _resources.number_negative_error );
			return false;
		}	
		return true;
	}
	
	private function _testDomain(n : Number) : Boolean
	{
		if( domain == ASType.INT && n%1 != 0 )
		{
			_prepareEvent( ValidationResultEvent.INVALID, n, _resources.number_integer_error );
			return false;
		}	
		return true;
	}
	
	private function _testMaxValue(n : Number) : Boolean
	{
		if( !isNaN(maxValue) && n > maxValue)
		{
			_prepareEvent( ValidationResultEvent.INVALID, n, _resources.number_exceed_max_error );
			return false;
		}	
		return true;
	}
	
	private function _testMinValue(n : Number) : Boolean
	{
		if( !isNaN(minValue) && n < minValue)
		{
			_prepareEvent( ValidationResultEvent.INVALID, n, _resources.number_lower_than_min_error );
			return false;
		}	
		return true;
	}
	
	private function _testPrecision(n : Number) : Boolean
	{
		if( !isNaN(precision) )
		{
			var s : String = n.toString();
			var decimal : String = s.substr( s.indexOf( "." ) );
			if( decimal.length > precision )
			{
				_prepareEvent( ValidationResultEvent.INVALID, n, _resources.number_precision_error );
				return false;
			}
		}	
		return true;
	}
	
}